package com.flyco.modules.system.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.util.PasswordUtil;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.system.entity.SysDepartRole;
import com.flyco.modules.system.entity.SysRole;
import com.flyco.modules.system.entity.SysUser;
import com.flyco.modules.system.entity.SysUserRole;
import com.flyco.modules.system.service.ISysRoleService;
import com.flyco.modules.system.service.ISysUserRoleService;
import com.flyco.modules.system.service.ISysUserService;
import com.flyco.modules.system.vo.SysUserDTO;
import com.flyco.modules.system.vo.SysUserQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author flyco
 * @since 2018-12-20
 */
@Slf4j
@Api(tags="门店用户")
@RestController
@RequestMapping("/f/sys/userV2")
public class SysUserControllerV2 {
	@Autowired
	private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysUserRoleService userRoleService;

    /**
     * 门店用户列表
     */
    @ApiOperation(value="门店用户列表", notes="门店用户列表")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result<IPage<SysUser>> queryPageList(SysUserQuery query, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
		Result<IPage<SysUser>> result = new Result<>();
        SysUser user = new SysUser();
        BeanUtil.copyProperties(query,user);
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        queryWrapper.eq("partner_id",1000L).eq("type","storeApp");
		Page<SysUser> page = new Page<>(pageNo, pageSize);
		IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);

		//查询角色名字，门店名字，状态名字
        if(StrUtil.isBlank(query.getId()) && pageList.getRecords()!=null && pageList.getRecords().size()>0){
            List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
            Map<String, SysDepartRole> roleMap = sysUserService.sysDepartRoleDetails(userIds);
            Map<String, List<StmStoreInfo>> storeListMap = sysUserService.stmStoreInfoDetails(userIds);

            pageList.getRecords().forEach(sysUser -> {
                SysDepartRole role = roleMap.get(sysUser.getId());
                if(role!=null){
                    sysUser.setRoleName(role.getRoleName());
                }
                List<StmStoreInfo> stmStoreInfos = storeListMap.get(sysUser.getId());
                if(stmStoreInfos!=null){
                    sysUser.setStoreNames(stmStoreInfos.stream().map(StmStoreInfo::getName).collect(Collectors.joining(",")));
                }
                if(sysUser.getStatus()==1){
                    sysUser.setStatusName("正常");
                }else{
                    sysUser.setStatusName("冻结");
                }
            });
        }

        //userId不为空，就查询一条详细记录
        if(StrUtil.isNotBlank(query.getId()) && pageList.getRecords()!=null && pageList.getRecords().size()==1){
            //查询关联的角色和授权的门店
            Map<String, Object> detail = sysUserService.detail(query.getId());
            pageList.getRecords().get(0).setRoleMap(detail);
        }

        result.setSuccess(true);
        result.setResult(pageList);
        log.info(pageList.toString());
        return result;
	}

    @ApiOperation(value="新增门店用户", notes="新增门店用户")
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Result add(@RequestBody SysUserDTO userDTO) {
        if(StrUtil.isBlank(userDTO.getUsername()) || StrUtil.isBlank(userDTO.getRealname()) || StrUtil.isBlank(userDTO.getPassword())){
            return Result.error("必传参数不能为空");
        }
        if(!userDTO.getUsername().matches("^1\\d{10}$")){
            return Result.error("账号格式不正确，只能输入手机号");
        }
        sysUserService.addUser(userDTO);
        return Result.ok("添加成功！");
	}

    @ApiOperation(value="编辑门店用户", notes="编辑门店用户")
	@RequestMapping(value = "/edit", method = RequestMethod.PUT)
	public Result edit(@RequestBody SysUserDTO userDTO) {
        if(StrUtil.isBlank(userDTO.getUserId())){
            return Result.error("userId不能为空");
        }
        SysUser sysUser = sysUserService.getById(userDTO.getUserId());
        if(sysUser==null) {
            return Result.error("未找到用户信息");
        }

        userDTO.setUsername(sysUser.getUsername());
        sysUserService.updateUser(userDTO);

        return Result.ok("更新成功！");
	}

    @ApiOperation(value="修改密码", notes="修改密码")
    @RequestMapping(value = "/edit-pwd", method = RequestMethod.PUT)
    public Result editPwd(@RequestBody SysUserDTO userDTO) {
        if(StrUtil.isBlank(userDTO.getUsername()) || StrUtil.isBlank(userDTO.getPassword())){
            return Result.error("参数不能为空");
        }
        SysUser sysUser = sysUserService.getOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUsername,userDTO.getUsername()));
        if(sysUser==null) {
            return Result.error("未找到用户信息");
        }

        //修改密码
        SysUser user = new SysUser();
        user.setId(sysUser.getId());
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(userDTO.getUsername(), userDTO.getPassword(), salt);
        user.setPassword(passwordEncode);
        sysUserService.updateById(user);

        return Result.ok("更新成功！");
    }

	/**
	 * 删除用户
	 */
    @ApiOperation(value="删除用户", notes="删除用户")
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		sysUserService.deleteUserV2(id);
		return Result.ok("删除用户成功");
	}

	/**
	  * 冻结&解冻用户
	 */
    @ApiOperation(value="冻结&解冻用户", notes="冻结&解冻用户")
	@RequestMapping(value = "/frozenBatch", method = RequestMethod.PUT)
	public Result frozenBatch(@RequestBody SysUserDTO sysUserDTO) {
        SysUser sysUser = new SysUser();
        sysUser.setId(sysUserDTO.getUserId());
        sysUser.setStatus(sysUserDTO.getStatus());
        sysUserService.updateById(sysUser);

        return Result.ok("操作成功！");
    }

    /**
     * 获取当前用户
     */
    @GetMapping("/getCurrentUser")
    public Result getCurrentUser() {
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        currentUser.setOrderCheckUserFlag(0);
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<SysRole>();
        queryWrapper.eq(SysRole::getRoleName, "跟单员");
        List<SysRole> roleList = roleService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(roleList)) {
            List<String> roleIds = roleList.stream().map(SysRole::getId).collect(Collectors.toList());
            List<SysUserRole> userRoleList = userRoleService.getByRoleIds(roleIds);
            if (!CollectionUtils.isEmpty(userRoleList)) {
                userRoleList.forEach(item ->
                {
                    if (item.getUserId().equals(currentUser.getId())) {
                        currentUser.setOrderCheckUserFlag(1);
                    }
                });
            }
        }
        return Result.ok(currentUser);
    }
}
